﻿namespace Bigway.Common.Extensions;

public static class AsyncEnumerableExtensions
{
    public static async ValueTask<List<TSource>> ToListAsync<TSource>(this IAsyncEnumerable<TSource>? source, CancellationToken cancellationToken = default)
    {
        ArgumentNullException.ThrowIfNull(source); 
        var list = new List<TSource>();

        await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
            list.Add(item);

        return list;
    }

    public static async ValueTask<IEnumerable<TSource>> ToEnumerableAsync<TSource>(this IAsyncEnumerable<TSource>? source, CancellationToken cancellationToken = default)
    {
        ArgumentNullException.ThrowIfNull(source);
        var enumerable = Enumerable.Empty<TSource>();

        await foreach (var item in source.WithCancellation(cancellationToken).ConfigureAwait(false))
            enumerable = enumerable.Append(item);

        return enumerable;
    }
}